import {useEffect, useState} from 'react'
import EchartsCtr from 'echarts'
import 'echarts/lib/chart/bar'
import 'echarts/theme/macarons'
import React from 'react'
import {Card} from 'antd'
import styles from './index.module.scss';

/**
 * 扇形图
 */
const CommandStatsChart: React.FC<{ commandStats: {} | undefined }> = (props) => {

  let commandStatsChart: HTMLDivElement;

  const {commandStats} = props
  const [lineChart, setLineChart] = useState<any>()

  useEffect(() => {
    const instance: any = EchartsCtr.init(commandStatsChart, "macarons")
    instance.showLoading()
    // 设置到state
    setLineChart(instance)
    // 开启自适应
    window.addEventListener('resize', instance.resize)
    // 关闭监听
    return () => {
      window.removeEventListener('resize', instance.resize)
    }
  }, [])

  useEffect(() => {
    if (!lineChart) {
      return
    }
    setEcharts(lineChart)
    lineChart.resize()
  }, [props])

  const setEcharts = (instance: any | undefined = undefined) => {
    const ctr = instance || lineChart
    if (!ctr) return

    // 设置参数
    ctr.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      legend: {
        left: 'center',
        bottom: '10',
      },
      series: [
        {
          name: '命令统计',
          type: 'pie',
          roseType: 'radius',
          radius: [15, 95],
          center: ['50%', '38%'],
          data: commandStats,
          animationEasing: 'cubicInOut',
          animationDuration: 2600
        }
      ]
    })
    ctr.hideLoading()
  }

  return (
    <Card title="命令统计" style={{margin: '20px 20px 20px 0', height: '410px'}}>
      <div
        ref={(ref: HTMLDivElement) => commandStatsChart = ref}
        className={styles.commandStatsChart}
      >
      </div>
    </Card>
  )
}

export default CommandStatsChart
